//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "PromotionSearchViewController.h"
#import "RestaurantDetailViewController.h"
#import "LoadMoreCell.h"
#import "PromotionCell.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "config.h"
#import "OMGToast.h"
@interface PromotionSearchViewController ()

@end

@implementation PromotionSearchViewController
@synthesize lbAddress;
@synthesize lbTitle;
@synthesize uvContent;
@synthesize wvContent;
@synthesize mainTable;
@synthesize reqSearch;
@synthesize reqSearchMore;
@synthesize reqNews;
@synthesize lbAuthor;
@synthesize lbTime;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    backList = false;
    pageIndex=1;
    lbAddress.text = [[Config Instance]getLocation];
    uvContent.hidden = YES;
    wvContent.delegate = self;
    
    [self startRequest];
    
}
- (void)startRequest
{
   if(!loadingView)
   {
        loadingView = [[RequestLoadingView alloc]
                            initRequestLoadingView:self
                              queueFinishSelector:nil
                                 viewFrame:LoadingViewFrame];
   }
    
    [self getSearchResult];
    
    [loadingView addRequestToQueue:reqSearch];
    
    [loadingView startRequestQueue];
    
}
- (void) getSearchResult{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_promotionList];
    reqSearch=[ASIFormDataRequest requestWithURL:url];
    [reqSearch setPostValue:[NSString stringWithFormat:@"%d",pageIndex++] forKey:@"pageIndex"];
    [reqSearch setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance] getCityId]] forKey:@"cityID"];
    [reqSearch setDidFinishSelector:@selector(finishSearch:)];
    [reqSearch setShouldAttemptPersistentConnection:NO];
    [reqSearch setDelegate: self];
    isSearchFinished = false;

    if (!loadingView.bFirstRequest)
    {
        [reqSearch startAsynchronous];
    }
}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)finishSearch:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    isSearchFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    
    tableDataArray = [dic valueForKey:@"data"];
    returnCount = [tableDataArray count];
    if (returnCount==0) {
        [OMGToast showWithText:@"暂无促销信息。" bottomOffset:100];
    }

    [mainTable reloadData];
    [Config setExtraCellLineHidden:mainTable];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
    isSearchFinished = true;
    isSearchMoreFinished = true;
    isNewsFinished = true;
}

- (void)viewDidUnload
{
    [self setMainTable:nil];
    [self setLbAddress:nil];
    [self setUvContent:nil];
    [self setWvContent:nil];
    [self setLbTitle:nil];
    [self setLbTime:nil];
    [self setLbAuthor:nil];
    [self setLbTitle:nil];
    [self setLbMainTitle:nil];
    [self setBtMerchant:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        self.title=@"搜索结果";
//    }
//    return self;
//}
// customize the number of rows in the table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        return 60;
    }else{
        return 40;
    }
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"PromotionCellIdentifier";
    
        
    if([indexPath row] < ([tableDataArray count])) {
        
        PromotionCell *cell = (PromotionCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"PromotionCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
       }
        
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        
        cell.lbName.text = [item valueForKey:@"MERCHANT_NAME"];
        cell.lbTitle.text = [item valueForKey:@"TITLE"];
        cell.lbTime.text = [[item valueForKey:@"UPDATE_TIME"] stringByReplacingOccurrencesOfString:@"T" withString:@" "];
        cell.lbClick.text =[ NSString stringWithFormat:@"%d" , [[item valueForKey:@"CLICK"] intValue ]];// ==[NSNull null]?@"未知" : [item valueForKey:@"CLICK"];
        
        return cell;

    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
          
          if(returnCount<pageSize){
              cell.lbText.text=@"";
              cell.hidden = true;
          }else{
              //创建loadMoreCell
              cell.lbText.text=str_more;
          }
          cell.textLabel.textAlignment = UITextAlignmentCenter;
          cell.detailTextLabel.text=@"";
          cell.imageView.image =nil;
          return cell;

    }
    
}
//-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
//{
//    UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
////    cell.imageView.image = image;
//    cell.imageView.image = [image copy];
//
//}


- (IBAction)showMerchant:(id)sender {
    if([TypeArray count]==1)
    {
        RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
        //传递商户id参数    
        view.merchantId = merchantId;
        view.merchantType = oneType;
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
    }
    else
    {
        LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择类型" options:TypeArray fullHeight:100];
        lplv.name = @"type";
        lplv.selectedIndex = 0;
        lplv.delegate = self;
        [lplv showInView:self.view animated:YES];
    }
    
}

- (IBAction)doBack:(id)sender {
    if (backList) {
        uvContent.hidden = YES;
        backList = false;
        _btMerchant.hidden = YES;
        _lbMainTitle.text = @"最新促销";

    }else{
        if(!isSearchFinished){
            [reqSearch clearDelegatesAndCancel];
            [reqSearch cancel];
        }if(!isSearchMoreFinished){
            [reqSearchMore clearDelegatesAndCancel];
            [reqSearchMore cancel];
        }if(!isNewsFinished){
            [reqNews clearDelegatesAndCancel];
            [reqNews cancel];
        }

        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction)btnDetail:(id)sender {
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == [tableDataArray count]) {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
//        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
//        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?pageIndex=%d",url_promotionList,pageIndex++]] ;
        reqSearchMore = [ASIFormDataRequest requestWithURL:url];
        [reqSearchMore setPostValue:@"1" forKey:@"cityID"];
        [reqSearchMore setDidFinishSelector:@selector(appendTableWith:)];
        [reqSearchMore setShouldAttemptPersistentConnection:NO];
        reqSearchMore.delegate = self;
        isSearchMoreFinished = false;
        [reqSearchMore startAsynchronous];
//        NSString *jsonStr = [request responseString];
//        
//        NSDictionary *dic = [jsonStr JSONValue];
//        NSMutableArray *array = [dic valueForKey:@"data"];
//        returnCount = [array count];
//        [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
//        [dic release];
//        [array release];
        return;
    }else{
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?newsID=%d",url_promotionContent,[[item objectForKey:@"NEWS_ID"] intValue]]] ;
        merchantId = [[item objectForKey:@"MERCHANT_ID"] intValue];
        lbTitle.text = [item objectForKey:@"TITLE"];
        reqNews = [ASIHTTPRequest requestWithURL:url];
        isNewsFinished = false;
        reqNews.delegate = self;
        [reqNews setDidFinishSelector:@selector(finishNews:)];
        [reqNews setShouldAttemptPersistentConnection:NO];
        [reqNews startAsynchronous];
        
    }
    //其他cell的事件
    
}
-(void) finishNews:(ASIHTTPRequest *)request
{   
    isNewsFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [[jsonStr JSONValue] valueForKey:@"data"];
    backList = true;
    uvContent.hidden = NO;
    _btMerchant.hidden = NO;
//    NSLog(@"%@",[dic objectForKey:@"content"]);
    if ([dic objectForKey:@"content"] != [NSNull null]) {
        [wvContent loadHTMLString:[dic objectForKey:@"content"]
                          baseURL:nil];
    }else
        [wvContent loadHTMLString:@""
                          baseURL:nil];

    NSMutableArray *typeTemp= [[NSMutableArray alloc] initWithArray: [dic objectForKey:@"merchantType"]];
    TypeArray= [[NSMutableArray alloc] initWithCapacity:3];
    if(typeTemp.count==1)
    {
        oneType=[[[typeTemp lastObject] objectForKey:@"typeID"] intValue];
    }
    for(int i=0;i<[typeTemp count];i++)
    {
        [TypeArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:[[typeTemp objectAtIndex:i] objectForKey:@"name"],@"type",nil]];
    }
    lbAuthor.text = [NSString stringWithFormat:@"发布者:%@",[dic valueForKey:@"author"]];
    lbTime.text = [NSString stringWithFormat:@"时间:%@",[dic valueForKey:@"updateTime"]];
    _lbMainTitle.text = @"促销详情";
}
#pragma mark - UIWebView Delegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *requestURL =[request URL];
    if (([[requestURL scheme] isEqualToString: @"http"] || [[requestURL scheme] isEqualToString:@"https"] || [[requestURL scheme] isEqualToString: @"mailto" ])
        && (navigationType == UIWebViewNavigationTypeLinkClicked)) {
        return ![[UIApplication sharedApplication] openURL:requestURL];
    }
    return YES;
}
-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    isSearchMoreFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount = [data count];
    //    [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [self.mainTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
}


- (IBAction)doClose:(id)sender {
    uvContent.hidden = YES;
}

- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex options:(NSArray *)_options didSelectedTypeIndex:(NSInteger)anTypeIndex
{
    RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
    //传递商户id参数
    view.merchantId = merchantId;
    view.merchantType = anIndex+1;
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
}
@end
